/*
 * 产品页面视图
 * @Author: ljb
 * @Date: 2018-03-27 17:52:07
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-10-30 16:48:09
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    .v-store-product-views {
        padding: 20px;
	}
	@deep: ~">>>";
	@{deep} .ivu-modal {
		top: 20px;
	}
	@{deep} .vertical-middle-modal .ivu-modal-body{
		min-height: 200px;
	}
	@{deep} .edit-product-modal .ivu-modal-body{
		min-height: 900px;
	}
</style>

<template>

	<div class="v-store-product-views">

		<Tabs
			v-model="tag_name"
			type="card"
			@on-click="changeTab">

			<TabPane
				:label="$t('common.create')"
				name="新增">

				<product-create
					ref="create"
					:product-tags="product_tags"
					:brands="brands"
					:group-brands="group_brands"
					:outer-chain="outer_chain"
					:positions="body_positions"
					:categories="categories"
					:group-categories="group_categories"
					:products="products.data"
					:taobao-item="getTaobaoItem"
					:models-group="assets"
					:show-taobao="show_taobao_detail"
					:loading="button_loading"
					:cosmetic-materials="cosmetic_materials"
					@post="postData"
					@taobao="fetchTaoBaoUrl"
					@detail="showDetailModal"
					@clear="clearTaoBaoDetail"
					@remove="removeTaoBaoDetailButton"
					@syncSale="syncSale"
					@syncInventory="syncInventory"
				/>

			</TabPane>

			<TabPane
				:label="$t('common.check')"
				name="查看">

				<!-- 搜索组件 -->
				<search-form
					:brands="brands"
					:categories="categories"
					:group-categories="group_categories"
					@search="confirmSearch"
					@export="confirmExcel"/>

				<product-index
					:loading="table_loading"
					:product-tags="product_tags"
					:brands="brands"
					:group-brands="group_brands"
					:brands-list="brandsList"
					:categories="categories"
					:group-categories="group_categories"
					:products="products.data"
					:cosmetic-materials="cosmetic_materials"
					@edit-customer-product="handleCustomerProductEdit"
					@update-customer-product-state="handleCustomerProductUpdate"
					@change-state="handleStateChange"
					@edit="productDetail"
					@delete="deleteProduct"
					@sort="handleSort"/>

				<br>

				<!-- 分页组件 -->
				<Row
					type="flex"
					justify="center">
					<Page
						:total="products.total"
						:current="products.current_page"
						:page-size="parseInt(products.per_page,10)"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>

			</TabPane>
		</Tabs>

		<Modal
			v-model="show_modal"
			:title="$t('product.update_product')"
			class-name="edit-product-modal">

			<!-- 产品编辑组件 -->
			<product-edit
				v-if="show_modal"
				ref="edit"
				:product-tags="product_tags"
				:brands="brands"
				:group-brands="group_brands"
				:outer-chain="outer_chain"
				:products="products.data"
				:categories="categories"
				:group-categories="group_categories"
				:models-group="assets"
				:product-detail="product_detail"
				:positions="body_positions"
				:show-modal="show_modal"
				:taobao-item="getTaobaoItem"
				:show-taobao-modal="show_taobao_modal"
				:loading="button_loading"
				:cosmetic-materials="cosmetic_materials"
				@update="updateProduct"
				@taobao="fetchTaoBaoUrl"
				@detail="showDetailModal"/>

			<div slot="footer"/>

		</Modal>

		<Modal
			v-model="show_taobao_modal"
			:title="$t('product.tb_product_detail')"
			class-name="vertical-middle-modal">

			<!-- 产品编辑组件 -->
			<detail-modal
				:show-taobao-modal="show_taobao_modal"
				:taobao-item="taobao_item"
				@comfirmTaoBaoDetail="ensureTaoBoaDetail"/>

			<div slot="footer"/>

		</Modal>

		<!-- BEGIN: customer 商品编辑 -->
		<Modal
			v-model="is_customer_product_form_visible"
			:title="$t('product.edit_customer_product')"
			class-name="vertical-middle-modal">

			<CustomerProductEdit
				v-if="is_customer_product_form_visible"
				:default-form="customer_product_form"
				@update="handleCustomerProductUpdate"/>

			<div slot="footer"/>

		</Modal>
		<!-- END: customer 商品编辑 -->

	</div>

</template>

<script>

import API_LIST from 'src/API_LIST';

import { mapMutations, mapGetters } from 'vuex';

import qs from 'qs';
import { deleteEmptyValue } from 'src/utils/utils';
import productCreate from './create';
import productIndex from './index';
import productEdit from './edit';
import searchForm from './search-form';
import detailModal from './taobao-detail';
import CustomerProductEdit from './customer-product-edit';

export default {

	name: 'ProductViews',

	components: {
		productCreate,

		productIndex,

		productEdit,

		searchForm,

		detailModal,

		CustomerProductEdit,
	},
	data() {
		return {
			query_info: {
				page: 1,

				per_page: 20,

				is_sale: '',

				is_deleted: '',

				is_hot: '',

				is_new: '',

				has_youzan: '',

				brand_id: '', // 品牌

				category_id: '', // 类别

				keyword: '',

				sort_column: '',

				sort_by: '',

				product_type: 'store_customer',
			},

			// search_info: {

			// 	page: 1,

			// 	per_page: 20,

			// }, // 分页信息

			tag_name: '新增',

			show_taobao_detail: false, // 淘宝详情按钮显示

			show_taobao_modal: false, // 淘宝详情弹框

			table_loading: false, // 表格更新时的loading

			show_modal: false, // 弹框的控制

			// show_status_modal: false,	// 是否显示产品状态编辑的弹框

			outer_chain: [], // 外链的类型

			product_detail: {}, // 产品详情

			products: {
				data: [],
				per_page: 20,
				current_page: 1,
				total: 0,
			}, // 产品列表

			categories: [], // 产品种类

			brands: {}, // 产品品牌

			product_tags: {}, // 产品的标签

			assets: [], // 产品模型

			taobao_item: {}, // 淘宝商品详情

			button_loading: false, // 获取淘宝商品详情按钮的loading

			is_customer_product_form_visible: false, // 是否显示 customer 商品

			customer_product_form: {
				product_id: null,
				is_deleted: null,
				priority: null,
				is_sale: null,
			}, // customer 商品表单

			body_positions: [],

			group_categories: [], // 产品种类成组

			cosmetic_materials: [], // 材质管理信息

			group_brands: [], // 系列信息

			brandsList: [], // 系列列表信息

		};
	},

	computed: {

		...mapGetters('userToken', [
			'getToken',
		]),

		getTaobaoItem() {
			return this.taobao_item;
		},

	},
	mounted() {
		this.fetchProductCreateInfo();
	},
	methods: {

		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
		 * 导出excel表格
		 * @return {undefined}
		 */
		confirmExcel(search_form) {
			const query = Object.assign({ token: this.getToken }, search_form);
			window.open(`${API_LIST.STORE_EXPORT_EXCEL}?${qs.stringify(query)}`);
		},

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			if (tab_name === '查看') {
				this.fetchProductList(this.query_info);

				this.$refs.create.handleReset('formValidate');

				this.taobao_item = {};
			} else {
				this.products.data = [];

				this.taobao_item = {};

				this.show_taobao_detail = false;
			}
		},

		/**
         * @function {显示淘宝详情弹窗}
         * @param {Object} record {淘宝商品详情对象}
         * @return {undefined}
         */
		showDetailModal(record) {
			if (record) {
				this.taobao_item = JSON.parse(record);
			}

			this.show_taobao_modal = true;
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			Object.assign(this.query_info, {
				page: pageNumber,
			});
			this.fetchProductList(this.query_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			Object.assign(this.query_info, {
				page: null,
				per_page,
			});
			this.fetchProductList(this.query_info);
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch(form) {
			Object.assign(this.query_info, form, { page: '' }); // 确认搜索page重置为空
			this.fetchProductList(this.query_info);
		},

		// /**
		//  * 查看产品的状态详情
		//  * @param  {Object} detail {查看的产品详情}
		//  * @return {undefined}
		//  */
		// showProductStatus(detail) {
		// 	this.product_detail = detail;

		// 	this.show_status_modal = true;
		// },

		/**
		 * 同步有赞在售商品
		 * @return {undefined}
		 */
		syncSale() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.STORE_YOUZAN_SYNC_SALE)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.sync_success'));
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})
				.finally(this.closeSpin);
		},

		/**
		 * 同步有赞仓库商品
		 * @return {undefined}
		 */
		syncInventory() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.STORE_YOUZAN_SYNC_INVEN)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.sync_success'));
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})
				.finally(this.closeSpin);
		},

		/**
		 * 更新状态
		 * @param  {Object} param {更新状态需要的参数}
		 * @return {undefined}
		 */
		updateStatus(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.patch(API_LIST.STORE_PRODUCT_STATUS, param)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.taobao_item = {};

					this.fetchProductList(this.query_info);

					// this.show_status_modal = false;

					this.product_detail = null;
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})

				.finally(this.closeSpin);
		},

		/**
         * 新增产品的post数据
         * @return {undefined}
         */
		postData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.STORE_PRODUCT, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('formValidate');
				})
				.catch((err) => {
					this.$Message.error(err.message);
				})
				.then(this.closeSpin);
		},

		/**
         * 获取淘宝商品链接URL
         * @return {undefined}
         */
		fetchTaoBaoUrl(param) {
			this.button_loading = true;

			const query_str = qs.stringify(param);

			this.$http.post(`${API_LIST.TAOBAO_URL}?${query_str}`)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.taobao_item = data.result;

					this.$Message.success(this.$t('common.fetch_product_success'));

					this.show_taobao_detail = true;
				})

				.catch(() => {
					this.taobao_item = {};

					this.show_taobao_detail = false;

					this.$Modal.confirm({

						title: this.$t('product.tip'),

						content: this.$t('product.request_product_fail'), // '获取商品信息失败，是否手动填写信息?',

						onOk: () => {
							this.show_taobao_modal = true;

							this.show_taobao_detail = true;
						},

						onCancel: () => {},
					});
				})

				.then(() => {
					this.button_loading = false;
				});
		},

		/**
         * 查看产品详情
         * @param  {string} id {产品详情的id}
         * @return {undefined}
         */
		productDetail(detail) {
			this.product_detail = detail;

			this.show_modal = true;
		},

		/**
         * 更新产品信息
         * @param  {Object} param {需要更新的参数对象}
         * @return {undefined}
         */
		updateProduct(id, param) {
			this.showSpin();

			this.$http.post(`${API_LIST.STORE_PRODUCT}/${id}`, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.show_modal = false;

					this.fetchProductList(this.query_info);
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
         * 删除产品
         * @param  {string} id {需要删除的产品的id}
         * @return {undefined}
         */
		deleteProduct(id) {
			this.$Modal.confirm({
				title: this.$t('product.tip'), // '温馨提示',
				content: this.$t('product.is_delete'), // '删除之后将无法恢复，确定吗？',
				onOk: () => {
					const param = {
						_method: 'DELETE',
					};

					this.table_loading = true;

					this.$http.post(`${API_LIST.STORE_PRODUCT}/${id}`, param)
						.then(({ data }) => {
							if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

							this.fetchProductList(this.query_info);

							this.$Message.success(this.$t('common.delete_success'));
						})
						.catch((err) => {
							this.$Message.error(err.message || err.statusText);
						})
						.then(() => { this.table_loading = false; });
				},
				onCancel: () => {},
			});
		},

		/**
         * 获取创建产品时所需信息
         * @return {undefined}
         */
		fetchProductCreateInfo() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.get(`${API_LIST.STORE_PRODUCT}/create`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.outer_chain = data.product_url_types;

					this.categories = data.categories;

					this.group_categories = data.group_categories;

					this.brands = data.brands;

					this.group_brands = data.brand_with_series;

					this.product_tags = data.product_tags;

					this.assets = data.assets_group;

					this.body_positions = data.body_positions;

					this.cosmetic_materials = data.cosmetic_materials;

					this.brandSeries(data.brand_with_series);
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		brandSeries(groupBrands) {
			for (let i = 0; i < groupBrands.length; i += 1) {
				for (let k = 0; k < groupBrands[i].brand_series.length; k += 1) {
					this.brandsList.push(groupBrands[i].brand_series[k]);
				}
			}
		},

		/**
         * 获取产品列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchProductList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.STORE_PRODUCT}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.products = data.products;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.table_loading = false; });
		},


		/**
		 * @function {确定修改的淘宝商品详情信息}
		 * @param  {Object} detail {淘宝商品详情}
		 * @return {undefined}
		 */
		ensureTaoBoaDetail(detail) {
			this.taobao_item = detail;

			this.show_taobao_modal = false;
		},

		/**
		 * @function {重置淘宝商品详情}
		 * @return {undefined} {}
		 */
		clearTaoBaoDetail() {
			this.taobao_item = {};
		},

		/**
		 * @function {隐藏淘宝商品详情修改按钮}
		 * @return {undefined} {}
		 */
		removeTaoBaoDetailButton() {
			this.show_taobao_detail = false;
		},

		/**
		 * 处理商品状体改变
		 * @param {object} row 商品详情
		 * @param {object} params 表单参数
		 * @return {undefined}
		 */
		handleStateChange({ index, ...params }) {
			this.product_detail = this.products.data[index];
			this.updateStatus(params);
		},

		/**
		 *  处理商家商品编辑
		 *  @param {Object} product 商品详情
		 */
		handleCustomerProductEdit(product) {
			this.customer_product_form.is_sale = product.show_is_sale;
			this.customer_product_form.is_deleted = product.store_pivot_customer_product_is_deleted;
			this.customer_product_form.priority = product.sort_priority;
			this.customer_product_form.product_id = product.id;
			this.is_customer_product_form_visible = true;
		},

		/**
		 * 更新商家商品
		 * @param {Object} form 表单
		 */
		updateCustomerProduct(form) {
			return this.$http.patch(API_LIST.STORE_UPDATE_CUSTOMER_PRODUCT, form)
				.then(({ data }) => {
					if (data.code !== 0) {
						throw new Error(data.error);
					} else {
						return data;
					}
				})
				.catch((error) => {
					this.$Message.error(error.message);
				});
		},

		/**
		 * 处理更新商家商品
		 * @param {Object} form 表单
		 */
		handleCustomerProductUpdate(form) {
			this.updateCustomerProduct(form)
				.then((result) => {
					if (result) {
						this.is_customer_product_form_visible = false;
						this.fetchProductList(this.query_info);
						this.$Message.success(this.$t('common.update_success'));
					}
				});
		},

		/**
		 *  处理商品排序
		 *  @param {Object} form 查询表单
		 */
		handleSort(form) {
			Object.assign(this.query_info, form);
			this.fetchProductList(this.query_info);
		},

	},
};
</script>
